package com.team.lostProperty.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.team.lostProperty.entity.Result;
import com.team.lostProperty.entity.User;
import com.team.lostProperty.service.UserService;
import com.team.lostProperty.utils.IdWorker;
import com.team.lostProperty.utils.MD5Utils;
import com.team.lostProperty.utils.TimeUtil;
import com.team.lostProperty.utils.UploadUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author duzq
 * @date 2020/07/25 14:24
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    private IdWorker idWorker = new IdWorker(1, 1, 1);

    @Resource
    private UserService userService;

    Result result = new Result();

    /**
     * 获取用户
     * @param page
     * @param limit
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/getUser")
    private Result getUser(String page, String limit) {
        List<User> user = userService.getUser(Integer.valueOf(page), Integer.valueOf(limit));
        if (user.size() >= 0) {
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(userService.getAllCount());
            result.setData(user);
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setCount(0);
            result.setData("");
        }
        return result;
    }

    @CrossOrigin
    @RequestMapping("/isLogin")
    private Result isLogin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user != null && !"".equals(user.toString())) {
            result.setCode(1);
            result.setMsg("成功");
            result.setData(user);
            result.setCount(0);
            return result;
        } else {
            result.setCode(-9999);
            result.setMsg("失败");
            result.setData("");
            result.setCount(0);
            return result;
        }
    }

    @CrossOrigin
    @RequestMapping("/quit")
    private Result quit(HttpServletRequest request) {
        SessionController.removeAttribute(request, "user");
        result.setCode(1);
        result.setMsg("成功");
        result.setData("");
        result.setCount(0);
        return result;
    }

    /**
     * 用户登陆Web
     *
     * @param request
     * @param userId
     * @param password
     * @return
     */
    @CrossOrigin
    @RequestMapping("/login")
    private Result Login(HttpServletRequest request, String userId, String password) {
        if (userId != null && !"".equals(userId.toString()) && password != null && !"".equals(password)) {
            User user = new User();
            if (isMobile(userId)) {
                user.setPhone(userId);
            } else {
                user.setUserId(Long.valueOf(userId));
            }
            user.setPassword(MD5Utils.UseMD5(password));
            List<User> userList = userService.login(user);
            if (userList.size() > 0) {
                result.setCode(1);
                result.setMsg("成功");
                request.getSession().setAttribute("user", userList.get(0));
                result.setData(userList.get(0));
                result.setCount(1);
            } else {
                result.setCode(-9999);
                result.setMsg("失败");
                result.setData("");
                result.setCount(0);
            }
            return result;
        } else {
            result.setCode(-9999);
            result.setMsg("失败");
            result.setData("");
            result.setCount(0);
            return result;
        }
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(final String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }


    /**
     *根据条件查询用户
     * @param request
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/selectUser")
    private Result selectUser(HttpServletRequest request) {
        User user = new User();
        if (!request.getParameter("id").equals("")) {
            user.setUserId(Integer.valueOf(request.getParameter("id")));
        }
        user.setUserName(request.getParameter("name"));
        user.setPhone(request.getParameter("phone"));
        if (!request.getParameter("sex").equals("")) {
            user.setGender(Integer.valueOf(request.getParameter("sex")));
        }

        List<User> pushInfoList = userService.selectUser(user);
        if (pushInfoList.size() >= 0) {
            result.setCode(0);
            result.setMsg("成功");
            result.setData(pushInfoList);
            result.setCount(userService.getAllCount());
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
            result.setCount(0);
        }
        return result;
    }

    /**
     * 根据ID删除用户
     * @param ids
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/deleteUser")
    private Result deleteUser(String ids) {
        int i = 0;
        if (ids != null && !ids.equals("")) {
            String[] str = ids.split(",");
            for (String id : str) {
                if (id != null && !id.equals("")) {
                    i = userService.deleteUser(Integer.valueOf(id));
                }
            }
        }
        if (i > 0) {
            result.setCode(0);
            result.setMsg("成功");
            result.setData("");
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
        }
        return result;
    }

    /**
     * 修改用户信息
     * @param request
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/updateUser")
    private Result updateUser(HttpServletRequest request) {
        String upuser = request.getParameter("upuser");
        User user = JSON.parseObject(upuser, User.class);
        int i = userService.updateUser(user);

        if (i > 0) {
            result.setCode(0);
            result.setMsg("成功");
            result.setData("");
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
        }
        return result;
    }

    @CrossOrigin
    @RequestMapping("addUser")
    public Result addUser(HttpServletRequest request) {
        String adduser = request.getParameter("adduser");
        User user = JSON.parseObject(adduser, User.class);
        user.setUserId(idWorker.nextId());
        user.setCreatedDate(TimeUtil.getNowDetailedTime());
        try {
            userService.addUser(user);
            result.setData("success");
            result.setCount(1);
            result.setCode(Result.RESULT_OK);
            result.setMsg("用户注册成功");
            return result;
        }catch (Exception e){
            result.setData("error");
            result.setCount(0);
            result.setCode(Result.RESULT_ERROR);
            result.setMsg("用户注册失败");
            return result;
        }
    }


    /**
     * web
      * @param request
     * @param phone
     * @param password
     * @return
     */
    @CrossOrigin
    @RequestMapping("addUserByPhone")
    public Result addUserByPhone(HttpServletRequest request, String phone, String password) {
        User user = new User();
        user.setPhone(phone);
        List<User> list = userService.selectUser(user);
        if (list.size() > 0) {
            result.setData("");
            result.setCount(0);
            result.setCode(Result.RESULT_ERROR);
            result.setMsg("用户注册失败,该电话号码已被使用");
            return result;
        }
        user.setUserId(idWorker.nextId());
        user.setUserName(phone);
        user.setPhone(phone);
        user.setNickName("");
        user.setAvatar("");
        user.setGender(1);
        user.setPassword(MD5Utils.UseMD5(password));
        user.setCreatedDate(TimeUtil.getNowDetailedTime());
        try {
            userService.addUser(user);
            request.getSession().setAttribute("user", user);
            result.setData("success");
            result.setCount(1);
            result.setCode(Result.RESULT_OK);
            result.setMsg("用户注册成功");
            return result;
        } catch (Exception e) {
            result.setData("");
            result.setCount(0);
            result.setCode(Result.RESULT_ERROR);
            result.setMsg("用户注册失败");
            return result;
        }
    }

    /**
     * web
     * @param file
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping("updateAvatar")
    public Result updateAvatar(MultipartFile file, HttpServletRequest request) {
        User user = (User) SessionController.getSession(request, "user");
        if (user == null) {
            result.setData("");
            result.setCount(-1);
            result.setCode(Result.RESULT_ERROR);
            result.setMsg("修改头像失败,请重新登陆");
            return result;
        } else {
            result = UploadUtil.fileSave(file, request, user.getPhone(), user.getPhone());
            if (result.getCode() == 0) {
                Map<String, String> map = (Map<String, String>) result.getData();
                String fileName = map.get("imgName");
                if (fileName != null && !fileName.isEmpty()) {
                    user.setAvatar(fileName);
                    userService.updateUser(user);
                    request.getSession().setAttribute("user", user);
                    return result;
                } else {
                    result.setData("");
                    result.setCount(-1);
                    result.setCode(Result.RESULT_ERROR);
                    result.setMsg("修改头像失败,重试");
                    return result;
                }
            }
            return result;

        }
    }

    /**
     * 修改用户信息Web
     *
     * @param request
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/updateUserByWeb")
    private Result updateUserByWeb(HttpServletRequest request, String nickName, int gender) {
        User user = (User) SessionController.getSession(request, "user");
        if (user == null) {
            result.setCode(result.RESULT_ERROR);
            result.setMsg("修改失败");
            result.setData("");
        } else {
            user.setNickName(nickName);
            user.setGender(gender);
        }
        int i = userService.updateUser(user);
        if (i > 0) {
            request.getSession().setAttribute("user", user);
            result.setCode(0);
            result.setMsg("成功");
            result.setData(user);
        } else {
            result.setCode(-9999);
            result.setMsg("修改失败");
            result.setData("");
        }
        return result;
    }

    @CrossOrigin
    @RequestMapping("/getUserByName")
    private Result getUserByName(String userName) {
        User user = userService.getUserByName(userName);
        Gson gson=new Gson();
        String date= gson.toJson(user);
        if (user!=null) {
            result.setCode(0);
            result.setMsg("成功");
            result.setData(date);
            result.setCount(userService.getAllCount());
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
            result.setCount(0);
        }
        return result;
    }
}
